package org.rqb.utils;

import lombok.extern.slf4j.Slf4j;
import org.rqb.Constant;
import org.rqb.config.MyConfig;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.*;
import java.util.Map;
import java.util.Properties;

@Slf4j
public class HttpUtil {
    private static Properties config = MyConfig.getConfig();
    private static String host = config.getProperty(Constant.PROXY_HOST);
    private static String port = config.getProperty(Constant.PROXY_PORT);
    private static String proxyEnable = config.getProperty(Constant.PROXY_ENABLED);

    private static Proxy proxy;
    static {
        if("true".equals(proxyEnable)) {
            if (host != null && port != null && !host.isEmpty() && !port.isEmpty()) {
                proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host,Integer.parseInt(port)));
            } else {
                proxy = Proxy.NO_PROXY;
            }
        }else {
            proxy = Proxy.NO_PROXY;
        }

    }




    public static InputStream getUrlInputStream(String url, Map<String,String> requestHeaders) {
        try {
            URL myUrl = new URL(url);
            URLConnection connection = myUrl.openConnection(proxy);
            requestHeaders.forEach(connection::setRequestProperty);

            return connection.getInputStream();
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }



    /**
     * 发送GET请求
     * @param urlStr 请求地址（完整的URL）
     * @return 响应结果（字符串）
     */
    public static String sendGet(String urlStr) {
        StringBuilder result = new StringBuilder();
        BufferedReader reader = null;
        HttpURLConnection connection = null;

        try {
            URL url = new URL(urlStr);
            connection = (HttpURLConnection) url.openConnection(proxy);
            // 设置请求方法为GET
            connection.setRequestMethod("GET");
            // 设置连接超时时间
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);

            // 获取响应码
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 读取返回内容
                reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
                String line;
                while ((line = reader.readLine()) != null) {
                    result.append(line);
                }
            } else {
                System.err.println("GET请求失败，响应码：" + responseCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭流和连接
            try {
                if (reader != null) reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (connection != null) connection.disconnect();
        }

        return result.toString();
    }



    /**
     * 发送POST请求
     * @param urlStr 请求地址（完整的URL）
     * @param params POST请求的参数字符串，如 "key1=value1&key2=value2"
     * @return 响应结果（字符串）
     */
    public static String sendPost(String urlStr, String params) {
        StringBuilder result = new StringBuilder();
        BufferedReader reader = null;
        HttpURLConnection connection = null;

        try {
            URL url = new URL(urlStr);
            connection = (HttpURLConnection) url.openConnection(proxy);

            // 设置POST基本参数
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);

            // 设置请求头
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestProperty("Charset", "UTF-8");

            // 写入参数
            if (params != null && !params.isEmpty()) {
                connection.getOutputStream().write(params.getBytes("UTF-8"));
                connection.getOutputStream().flush();
                connection.getOutputStream().close();
            }

            // 读取返回内容
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
                String line;
                while ((line = reader.readLine()) != null) {
                    result.append(line);
                }
            } else {
                System.err.println("POST请求失败，响应码：" + responseCode);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (reader != null) reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (connection != null) connection.disconnect();
        }

        return result.toString();
    }



    public static void updateProxy(Proxy proxy) {
        HttpUtil.proxy = proxy;
    }



}
